﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

using CNCSoft.EData;
using CNCSoft.EWinform.ERPApps;
using CNCSoft.EData.SqlServer;

using Common;

namespace CNCSoft.ErpApps.TMS
{
	/// <summary>
	/// Summary description for FormLogin.
	/// </summary>
	public class FormLoginTMS : System.Windows.Forms.Form {

        private System.Windows.Forms.TextBox txtUserID;
		private System.Windows.Forms.Button btnLogin;
        private System.Windows.Forms.TextBox txtPassword;
		private System.Windows.Forms.Button btnCancel;
        private System.Windows.Forms.DateTimePicker dtpWorkingDate;
        private System.Windows.Forms.ErrorProvider ep;
        private DevExpress.XtraEditors.ComboBoxEdit cboLanguage;
        private DevExpress.XtraEditors.LookUpEdit cboDonVi;
        private Label label4;
        private Label label3;
        private Label label2;
        private Label label1;
        private IContainer components;

		public FormLoginTMS(string connectionString) {
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			m_ConnectionString = connectionString;
		}

		public FormLoginTMS(WorkingSessionInfo wsInfo) {
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			_wsInfo = wsInfo;
		}

		public FormLoginTMS() {
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormLoginTMS));
            this.txtUserID = new System.Windows.Forms.TextBox();
            this.btnLogin = new System.Windows.Forms.Button();
            this.txtPassword = new System.Windows.Forms.TextBox();
            this.btnCancel = new System.Windows.Forms.Button();
            this.dtpWorkingDate = new System.Windows.Forms.DateTimePicker();
            this.ep = new System.Windows.Forms.ErrorProvider(this.components);
            this.cboLanguage = new DevExpress.XtraEditors.ComboBoxEdit();
            this.cboDonVi = new DevExpress.XtraEditors.LookUpEdit();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.ep)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.cboLanguage.Properties)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.cboDonVi.Properties)).BeginInit();
            this.SuspendLayout();
            // 
            // txtUserID
            // 
            this.txtUserID.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.txtUserID.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.txtUserID.Location = new System.Drawing.Point(449, 100);
            this.txtUserID.MaxLength = 20;
            this.txtUserID.Name = "txtUserID";
            this.txtUserID.Size = new System.Drawing.Size(243, 23);
            this.txtUserID.TabIndex = 0;
            this.txtUserID.TextChanged += new System.EventHandler(this.txtUserID_TextChanged);
            // 
            // btnLogin
            // 
            this.btnLogin.BackColor = System.Drawing.Color.WhiteSmoke;
            this.btnLogin.Cursor = System.Windows.Forms.Cursors.Hand;
            this.btnLogin.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnLogin.ForeColor = System.Drawing.SystemColors.ControlText;
            this.btnLogin.Location = new System.Drawing.Point(352, 333);
            this.btnLogin.Name = "btnLogin";
            this.btnLogin.Size = new System.Drawing.Size(127, 40);
            this.btnLogin.TabIndex = 3;
            this.btnLogin.Text = "&Login";
            this.btnLogin.UseVisualStyleBackColor = false;
            this.btnLogin.Click += new System.EventHandler(this.btnLogin_Click);
            // 
            // txtPassword
            // 
            this.txtPassword.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.txtPassword.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.txtPassword.Location = new System.Drawing.Point(449, 155);
            this.txtPassword.MaxLength = 20;
            this.txtPassword.Name = "txtPassword";
            this.txtPassword.PasswordChar = '*';
            this.txtPassword.Size = new System.Drawing.Size(243, 23);
            this.txtPassword.TabIndex = 1;
            this.txtPassword.TextChanged += new System.EventHandler(this.txtUserID_TextChanged);
            // 
            // btnCancel
            // 
            this.btnCancel.BackColor = System.Drawing.SystemColors.Control;
            this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.btnCancel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnCancel.ForeColor = System.Drawing.SystemColors.ControlText;
            this.btnCancel.Location = new System.Drawing.Point(511, 333);
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Size = new System.Drawing.Size(127, 40);
            this.btnCancel.TabIndex = 4;
            this.btnCancel.Text = "E&xit";
            this.btnCancel.UseVisualStyleBackColor = false;
            // 
            // dtpWorkingDate
            // 
            this.dtpWorkingDate.CalendarTitleBackColor = System.Drawing.Color.SlateGray;
            this.dtpWorkingDate.CustomFormat = "dd/MM/yyyy";
            this.dtpWorkingDate.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dtpWorkingDate.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
            this.dtpWorkingDate.Location = new System.Drawing.Point(449, 205);
            this.dtpWorkingDate.Name = "dtpWorkingDate";
            this.dtpWorkingDate.Size = new System.Drawing.Size(243, 30);
            this.dtpWorkingDate.TabIndex = 2;
            // 
            // ep
            // 
            this.ep.ContainerControl = this;
            this.ep.Icon = ((System.Drawing.Icon)(resources.GetObject("ep.Icon")));
            // 
            // cboLanguage
            // 
            this.cboLanguage.EditValue = "Tiếng Việt";
            this.cboLanguage.Location = new System.Drawing.Point(449, 258);
            this.cboLanguage.Name = "cboLanguage";
            this.cboLanguage.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.False;
            this.cboLanguage.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 12F);
            this.cboLanguage.Properties.Appearance.Options.UseFont = true;
            this.cboLanguage.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
            new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
            this.cboLanguage.Properties.Items.AddRange(new object[] {
            "Tiếng Việt",
            "English"});
            this.cboLanguage.Size = new System.Drawing.Size(243, 31);
            this.cboLanguage.TabIndex = 5;
            // 
            // cboDonVi
            // 
            this.cboDonVi.Location = new System.Drawing.Point(12, 338);
            this.cboDonVi.Name = "cboDonVi";
            this.cboDonVi.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 12F);
            this.cboDonVi.Properties.Appearance.Options.UseFont = true;
            this.cboDonVi.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
            new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
            this.cboDonVi.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
            new DevExpress.XtraEditors.Controls.LookUpColumnInfo("TenDonVi", "Đơn vị")});
            this.cboDonVi.Properties.DisplayMember = "TenDonVi";
            this.cboDonVi.Properties.NullText = "";
            this.cboDonVi.Properties.ValueMember = "MaDonVi";
            this.cboDonVi.Size = new System.Drawing.Size(226, 31);
            this.cboDonVi.TabIndex = 6;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.BackColor = System.Drawing.Color.Transparent;
            this.label1.Location = new System.Drawing.Point(301, 100);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(107, 25);
            this.label1.TabIndex = 7;
            this.label1.Text = "User name";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.BackColor = System.Drawing.Color.Transparent;
            this.label2.Location = new System.Drawing.Point(301, 154);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(98, 25);
            this.label2.TabIndex = 8;
            this.label2.Text = "Password";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.BackColor = System.Drawing.Color.Transparent;
            this.label3.Location = new System.Drawing.Point(301, 208);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(128, 25);
            this.label3.TabIndex = 9;
            this.label3.Text = "Working date";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.BackColor = System.Drawing.Color.Transparent;
            this.label4.Location = new System.Drawing.Point(301, 261);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(100, 25);
            this.label4.TabIndex = 10;
            this.label4.Text = "Language";
            // 
            // FormLoginTMS
            // 
            this.AcceptButton = this.btnLogin;
            this.AutoScaleBaseSize = new System.Drawing.Size(10, 23);
            this.AutoSize = true;
            this.BackColor = System.Drawing.Color.WhiteSmoke;
            this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
            this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.CancelButton = this.btnCancel;
            this.ClientSize = new System.Drawing.Size(740, 423);
            this.ControlBox = false;
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.cboDonVi);
            this.Controls.Add(this.cboLanguage);
            this.Controls.Add(this.btnCancel);
            this.Controls.Add(this.dtpWorkingDate);
            this.Controls.Add(this.btnLogin);
            this.Controls.Add(this.txtUserID);
            this.Controls.Add(this.txtPassword);
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "FormLoginTMS";
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "TMS - Login Manager";
            this.TopMost = true;
            this.Activated += new System.EventHandler(this.FormLoginTMS_Activated);
            this.Closing += new System.ComponentModel.CancelEventHandler(this.FormLoginTMS_Closing);
            this.Deactivate += new System.EventHandler(this.FormLoginTMS_Deactivate);
            this.Load += new System.EventHandler(this.FormLoginTMS_Load);
            ((System.ComponentModel.ISupportInitialize)(this.ep)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.cboLanguage.Properties)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.cboDonVi.Properties)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		private WorkingSessionInfo _wsInfo = null;

		private void btnLogin_Click(object sender, System.EventArgs e) {

			if (txtUserID.Text.Trim() == string.Empty) {
				ep.SetError(txtUserID, "Bạn vui lòng nhập tên đăng nhập !.");
				return;
			}
			
			//todo: Khong hieu tai sao lai goi login 2 lan ???.
			if (DoLogin()) {						
				
				this.DialogResult = DialogResult.OK;
			}		
		}

		private bool DoLogin() {
			this.Cursor = Cursors.WaitCursor;
			SqlConnection cnn = new SqlConnection();
			try {

				//Anti-hack
				string __userid = txtUserID.Text.Trim(), __pass = txtPassword.Text.Trim();
				if (__userid.IndexOfAny(new char[]{'\'', '\"', '%', '*'}) != -1) {
					ep.SetError(txtUserID, "Baby, don't hack me !.");
					return false;
				}
				if (__pass.IndexOfAny(new char[]{'\'', '\"', '%', '*'}) != -1) {
					ep.SetError(txtPassword, "Baby, don't hack me !.");
					return false;
				}
				//End of Anti-hack

				cnn.ConnectionString = m_ConnectionString;
				cnn.Open();
				SqlCommand cmd = new SqlCommand("SELECT UserID, ISNULL(FullName, '') as FullName FROM " + MenuManager.tUser + " "
					+ "WHERE (UserID = '" + __userid + "' AND "
					+ "Password = '" + __pass + "' AND "
					+ "ISNULL(IsLocked, 0) = 0)" , cnn);

				m_UserID = cmd.ExecuteScalar() as string;
				SqlDataReader sqldr = cmd.ExecuteReader();
				if (sqldr.Read()) {
					m_UserID = sqldr.GetValue(0).ToString();
					m_UserName = (string)sqldr.GetValue(1);
				} else {
					ep.SetError(txtUserID, "Đăng nhập không thành công. " +
						"Bạn vui lòng kiểm tra lại Tên đăng nhập/Mật khẩu.");
				}
				sqldr.Close();
				cmd.Dispose();

				workingDate = dtpWorkingDate.Value;
                m_Language = cboLanguage.EditValue.ToString();
                m_CompanyID = cboDonVi.EditValue.ToString();
                CompanyID = cboDonVi.EditValue.ToString();

				if (_wsInfo != null) {
					_wsInfo.UserID = m_UserID;
					_wsInfo.WorkingDate = workingDate;
                    //_wsInfo.Language = cboLanguage.EditValue.ToString();
				}
				if (m_UserID != null) { //Login successfuly
					_authenticated = true;
                    
                    return true;
				}

			}
			catch (Exception ex) {
				ep.SetError(txtUserID, ex.Message);
			}
			finally {
				try {
					cnn.Close();
					this.Cursor = Cursors.Default;
				} catch {}
			}						
			
			return false;
		}

		public WorkingSessionInfo createWSInfo() {
			if (!_authenticated) {
				throw new Exception("Programming Error: Before creating WSInfo, logining must be successful !.");
			}
			WorkingSessionInfo wsInfo = new WorkingSessionInfo(m_ConnectionString);
			wsInfo.UserID = m_UserID;
			wsInfo.WorkingDate = workingDate;
			wsInfo.ConnectionString = m_ConnectionString;
			wsInfo.UserName = m_UserName;
            wsInfo.Language = m_Language;
            wsInfo.CompanyID = m_CompanyID;
			return wsInfo;
		}

		public void supportStatusBar(StatusBar sb) {
			if (sb == null) return;

			sb.Panels.Clear();

			StatusBarPanel sbp = new StatusBarPanel();
			sbp.AutoSize = StatusBarPanelAutoSize.Spring;
			sb.Panels.Add(sbp);

			sbp = new StatusBarPanel();
			sbp.AutoSize = StatusBarPanelAutoSize.Contents;
			sbp.Alignment = HorizontalAlignment.Center;
			sb.Panels.Add(sbp);

			sbp = new StatusBarPanel();
			sbp.AutoSize = StatusBarPanelAutoSize.Contents;
			sbp.Alignment = HorizontalAlignment.Center;
			sb.Panels.Add(sbp);

			sbp = new StatusBarPanel();
			sbp.AutoSize = StatusBarPanelAutoSize.None;
			sbp.Alignment = HorizontalAlignment.Center;
			sbp.Width = 100;
			sb.Panels.Add(sbp);

			if (Authenticated && _wsInfo != null) {
				sb.Panels[1].Text = _wsInfo.WindowsMachineName + "." + _wsInfo.WindowsUserName;
				sb.Panels[2].Text = _wsInfo.SqlServerName + "." + _wsInfo.SqlServerDatabaseName + "." + _wsInfo.UserID;
                sb.Panels[3].Text = _wsInfo.WorkingDate.ToString("dd/MM/yyyy");
			}		
		}
		
		#region [ Attributes ]
		private string m_ConnectionString;
		private bool _authenticated;
		private bool _serverconnected;

		public string ConnectionString
		{
			get { return m_ConnectionString; }
			set { m_ConnectionString = value; }
		}

		public bool Authenticated {
			get { return _authenticated; }
		}

		public bool ServerConnected {
			get { return _serverconnected; }
		}

		public string TableNameOfUserList
		{
			get { return MenuManager.tUser; }
			set { MenuManager.tUser = value; }
		}

		private string m_UserID;
		public string UserID
		{
			get { return m_UserID; }
			set { m_UserID = value; }
		}

		private string m_UserName;
		public string UserName {
			get { return m_UserName; }
			set { m_UserName = value; }
		}

		private DateTime workingDate;
		public DateTime WorkingDate
		{
			get { return workingDate; }
			set { workingDate = value; }
		}

        private string m_CompanyID;
        public string CompanyID
        {
            get { return m_CompanyID; }
            set { m_CompanyID = value; }
        }
        
        private string m_Language;
        public string Language
        {
            get { return m_Language; }
            set { m_Language = value; }
        }

		#endregion	
	
        private BindingSource bindingSource_DonVi = new BindingSource();

		private void FormLoginTMS_Load(object sender, System.EventArgs e) {

            this._authenticated = false;
			this._serverconnected = false;

            if (GlobalVariable.WSInfo.Language != null || GlobalVariable.WSInfo.Language != "")
                cboLanguage.EditValue = GlobalVariable.WSInfo.Language;

            // Check where is firsly program setup

			if (_wsInfo != null) {
				m_ConnectionString  = _wsInfo.ConnectionString;
			}
			
			SqlConnectionInfo sqlcnInfo = new SqlConnectionInfo(m_ConnectionString);
			//lblConnectInfo.Text = "        Server:    " +sqlcnInfo.DataSource.ToUpper();
			try {

				int count = (int)SQLHelper.ExecuteScalar(m_ConnectionString, "Select count(*) from " +MenuManager.tUser);
				if (count == 0) {
				
					MessageBox.Show("Đây là lần đầu tiên khởi tạo chương trình, chúng tôi sẽ tạo một " +
						"user mặc định: test.", "Login Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

					SQLHelper.ExecuteNonQuery(m_ConnectionString, "Insert into " +MenuManager.tUser +"(UserId, FullName, Password) " +
						"values ('test', 'CNC Inc. Test user', '')");

					MenuManager mm = new MenuManager(m_ConnectionString);
					mm.ShowDialog(this);
					mm.Dispose();

					//UserID = "test";
                    UserID = GlobalVariable.WSInfo.getAppProperty("UserIDDefault");
                    if (UserID.ToLower() == "unknow")
                        UserID = PublicFunction.ReadFileText(GlobalVariable.WSInfo.ApplicationStartupPath + "\\LocalInformation.txt", 1);


				} else if ((int)SQLHelper.ExecuteScalar(m_ConnectionString, "Select count(*) from " +MenuManager.SYS_LIST_MENU) == 0) {

					MessageBox.Show("Bạn vui lòng khởi tạo Menu của hệ thống.", "Login Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

					MenuManager mm = new MenuManager(m_ConnectionString);
					mm.ShowDialog(this);
					mm.Dispose();
				}

				_serverconnected = true;

				

			} catch (Exception ex) {
				MessageBox.Show(this, "Không thể kết nối tới server [" +sqlcnInfo.DataSource +"], bạn vui lòng kiểm tra lại."
					+"\n\tErorcode: " +ex.Message,
					"Server Connect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			sqlcnInfo = null;
            if (UserID == string.Empty || UserID == null)
            {
                UserID = PublicFunction.ReadFileText(GlobalVariable.WSInfo.ApplicationStartupPath + "\\LocalInformation.txt", 1);
            }
            
			this.txtUserID.Text = UserID;
            
            SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM DM_DONVI", GlobalVariable.WSInfo.ConnectionString);
            DataTable dt = new DataTable("DM_DONVI");
            if (dt != null)
                dt.Clear();
            dataAdapter.Fill(dt);
            this.cboDonVi.Properties.DataSource = dt;
            
            //Don vi default o dong so 2
            cboDonVi.EditValue = UserID = PublicFunction.ReadFileText(GlobalVariable.WSInfo.ApplicationStartupPath + "\\LocalInformation.txt", 2);

            //Do phien ha (only me)
            if(txtUserID.Text == "TEST")
                txtPassword.Text = "357";
            
		}

		private void FormLoginTMS_Deactivate(object sender, System.EventArgs e) {
			this.Opacity = 0.8;
		}

		private void FormLoginTMS_Activated(object sender, System.EventArgs e) {
			this.Opacity = 1;
		}

		private void txtUserID_TextChanged(object sender, System.EventArgs e) {
			ep.SetError(txtUserID, null);
			ep.SetError(txtPassword, null);
		}

		private void FormLoginTMS_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
			if (!_authenticated) {
				this.m_UserID = null;
			}
		}
	
//		public bool ProcessCancelled {
//			get { return cancelled; }
//		}
			
	}
}
